package com.everflourish.yeah100.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.markingsystem.ProofreadCorrectActivity;
import com.everflourish.yeah100.act.questionlib.QuestionCommentActivity;
import com.everflourish.yeah100.act.questionlib.QuestionFavoriteActivity;
import com.everflourish.yeah100.act.questionlib.QuestionListActivity;
import com.everflourish.yeah100.entity.question.CancelQuestion;
import com.everflourish.yeah100.entity.question.Question;
import com.everflourish.yeah100.entity.question.QuestionUploadImage;
import com.everflourish.yeah100.http.HttpURL;
import com.everflourish.yeah100.ui.CircleImageView;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.ImageSelectHolder;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.ResourcesUtil;
import com.everflourish.yeah100.utils.StringUtil;
import com.everflourish.yeah100.utils.Yeah100;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/20.
 * 时间：2016/7/20
 */
public class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.QuestionHolder> {

    private Context mContext;
    private QuestionListActivity mActivity;
    private LayoutInflater mLayoutInflater;
    private List<Question> mList;
    private List<Question> mBakupList;
    private LoadDialog mLoadDialog;
    private RequestQueue mQueue;
    private String mExaminationId;
    private int mPosition;
    private QuestionImageAdapter mQuestionImageAdapter;

    public QuestionAdapter(Context mContext, Activity mActivity,
                           List<Question> mList, String examinationId, RequestQueue mQueue) {
        this.mContext = mContext;
        this.mActivity = (QuestionListActivity) mActivity;
        this.mList = mList;
        this.mQueue = mQueue;
        this.mExaminationId = examinationId;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    public QuestionHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.item_qustion, parent, false);
        QuestionHolder viewHolder = new QuestionHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(QuestionHolder holder, final int position) {
        Question question = mList.get(position);
        holder.seqNo.setText(question.getSeqNo());
        if (question.getComment() == null) {
            question.setComment("");
        }
        String comment = "<b>题目分析：</b>" + question.getComment();
        holder.questionCommentTv.setText(Html.fromHtml(comment));
        if (!question.getQuestionType().equals("3")) {  // 非主观题
            if (question.getAnswer().equals("")) {
                holder.questionStandardAnswerTv.setText("标准答案：无");
            } else {
                holder.questionStandardAnswerTv.setText("标准答案：" + question.getAnswer());
            }
        } else {
            holder.questionStandardAnswerTv.setVisibility(View.GONE);
        }
        QuestionImageAdapter questionImageAdapter = new QuestionImageAdapter(mContext, question.getImageUrls());
        holder.imageRcv.setLayoutManager(new LinearLayoutManager(mContext));
        holder.imageRcv.setAdapter(questionImageAdapter);
        if (question.getFavoriated() == 0) { // 未收藏
            holder.collectIv.setImageDrawable(ResourcesUtil.getDrawable(mContext, R.drawable.question_uncollect_selector));
        } else if (question.getFavoriated() == 1) { // 已收藏
            holder.collectIv.setImageDrawable(ResourcesUtil.getDrawable(mContext, R.drawable.question_collect_selector));
        }
        holder.itemAddIv.setOnClickListener(new MyOnclickListener(holder, position, questionImageAdapter));
        holder.deleteIv.setOnClickListener(new MyOnclickListener(holder, position, questionImageAdapter));
        holder.editIv.setOnClickListener(new MyOnclickListener(holder, position, questionImageAdapter));
        holder.collectIv.setOnClickListener(new MyOnclickListener(holder, position, questionImageAdapter));
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public class QuestionHolder extends RecyclerView.ViewHolder {

        private CircleImageView questionHeadCv;
        private TextView userNameTv;
        private TextView seqNo;
        private TextView questionCommentTv;
        private TextView questionStandardAnswerTv;
        private RecyclerView imageRcv;
        private ImageView deleteIv;
        private ImageView itemAddIv;
        private ImageView editIv;
        private ImageView collectIv;

        private LinearLayout itemLl;

        public QuestionHolder(View itemView) {
            super(itemView);
            questionHeadCv = (CircleImageView) itemView.findViewById(R.id.question_user_image);
            userNameTv = (TextView) itemView.findViewById(R.id.question_user_name_tv);
            seqNo = (TextView) itemView.findViewById(R.id.question_number_tv);
            questionCommentTv = (TextView) itemView.findViewById(R.id.question_statistic_tv);
            questionStandardAnswerTv = (TextView) itemView.findViewById(R.id.question_standard_answer);
            imageRcv = (RecyclerView) itemView.findViewById(R.id.question_capture_list);
            deleteIv = (ImageView) itemView.findViewById(R.id.item_question_delete);
            itemAddIv = (ImageView) itemView.findViewById(R.id.item_question_add);
            editIv = (ImageView) itemView.findViewById(R.id.item_question_edit);
            collectIv = (ImageView) itemView.findViewById(R.id.item_question_collect);
            itemLl = (LinearLayout) itemView.findViewById(R.id.question_item_ll);
        }
    }

    class MyOnclickListener implements View.OnClickListener {

        private QuestionHolder viewHolder;
        private int position;
        private QuestionImageAdapter questionImageAdapter;

        public MyOnclickListener(QuestionHolder viewHolder, int position, QuestionImageAdapter questionImageAdapter) {
            this.viewHolder = viewHolder;
            this.position = position;
            this.questionImageAdapter = questionImageAdapter;
        }

        @Override
        public void onClick(View v) {
            mPosition = position;
            mQuestionImageAdapter = questionImageAdapter;
            switch (v.getId()) {
                case R.id.item_question_add:
                    mActivity.upLoadType = 1;
                    mActivity.mImageSelectHolder.open(v, ImageSelectHolder.IMAGE_QUESTION);
                    break;
                case R.id.item_question_delete:

                    Intent questionIntent = new Intent(mContext,
                            ProofreadCorrectActivity.class);
                    questionIntent.putExtra(IntentUtil.QUESTIONLISTIMAGE, (ArrayList<String>)mList.get(position).getImageUrls());
                    questionIntent.putExtra(IntentUtil.QUESTIONLISTIMAGEINDEX, position);
                    mContext.startActivity(questionIntent);

//                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
//                    dialogBuilder.setMessage("确定要删除该题目吗？");
//                    dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            deleteQuestionRequest(mList.get(position));
//                        }
//                    });
//                    dialogBuilder.setNegativeButton("否", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                        }
//                    });
//                    dialogBuilder.show();
                    break;
                case R.id.item_question_edit:
                    Intent intent = new Intent(mContext,
                            QuestionCommentActivity.class);
                    intent.putExtra(IntentUtil.QUESTION_UPDATE, mList.get(position));
                    intent.putExtra(IntentUtil.EXAMINATION_ID, mExaminationId);
                    mActivity.startActivityForResult(intent, 0x140);
                    break;
                case R.id.item_question_collect:
                    final Question question = mList.get(position);
                    if (question.getFavoriated() == 0) { // 未收藏
                        Intent favoriteIntent = new Intent(mContext,
                                QuestionFavoriteActivity.class);
                        favoriteIntent.putExtra(IntentUtil.QUESTION_UPDATE, mList.get(position));
                        favoriteIntent.putExtra(IntentUtil.EXAMINATION_ID, mExaminationId);
                        mActivity.startActivityForResult(favoriteIntent, 0x150);
                    } else if (question.getFavoriated() == 1) { // 已收藏
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                        builder.setMessage("确定要取消收藏吗？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                unFavoriteQuestionRequest(setCancelQuestionList(question), question);
                            }
                        });
                        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.show();
                    }
                    break;
            }
        }
    }

    /**
     * 设置取消的参数
     *
     * @param question
     * @return
     */
    private List<CancelQuestion> setCancelQuestionList(Question question) {
        List<CancelQuestion> cancelQuestions = new ArrayList<CancelQuestion>();
        CancelQuestion cancelQuestion = new CancelQuestion();
        cancelQuestion.setQuestionId(question.getQuestionId());
        cancelQuestion.setTagIds(null);
        cancelQuestions.add(cancelQuestion);
        return cancelQuestions;
    }

    /**
     * 老师取消收藏题目请求
     *
     * @param cancelQuestions
     * @param question
     */
    private void unFavoriteQuestionRequest(List<CancelQuestion> cancelQuestions, final Question question) {
        mLoadDialog = LoadDialog.show(mContext, null, "取消中...", mQueue);
        JsonObjectRequest request = mActivity.mRequest.unFavoriteQuestionRequest(cancelQuestions,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        unFavoriteQuestionListener(response, question);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mActivity.mRequest.disposeError(mContext, mLoadDialog, error, "取消收藏失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 老师取消收藏题目监听
     *
     * @param response
     */
    private void unFavoriteQuestionListener(JSONObject response, Question question) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                question.setFavoriated(0);
                notifyDataSetChanged();
                MyToast.showShort(mContext, "取消收藏成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09191_000001E);
            } else if (resultCode.equals(ResultCode.result_300025E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09192_300025E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091999_999999E);
            } else {
                MyToast.showShort(mContext, "取消收藏失败");
            }
        } catch (Exception e) {
            LogUtil.e("Json异常", e);
            MyToast.showShort(mContext, "取消收藏失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 题目图片上传
     *
     * @param bitmap
     * @throws Exception
     */
    public void uploadImage(final Bitmap bitmap)
            throws Exception {
        String name = Yeah100.loginInfo.userInfo.name;
        String encoderName = CommonUtil.string2MD5(name);
        final File file = new File(Environment.getExternalStorageDirectory()
                + "/" + encoderName + "_" + System.currentTimeMillis() + ".jpg");
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        RequestParams params = new RequestParams();
        params.addHeader("tokenId", Yeah100.loginInfo.tokenId);
        HttpUtils httpUtils = new HttpUtils();
        String http = new HttpURL().URL_NEW_QUESTION_UPLOAD;
        params.addBodyParameter("outputStream", file);
        params.addBodyParameter("examinationId", mExaminationId);

        httpUtils.send(HttpMethod.POST, http, params,
                new RequestCallBack<Object>() {
                    @Override
                    public void onLoading(long total, long current,
                                          boolean isUploading) {
                        LogUtil.d(total + ":" + current + ":" + isUploading);
                    }

                    @Override
                    public void onStart() {
                        mLoadDialog = LoadDialog.show(mActivity, null, "正在上传...");
                    }

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        if (arg0 != null && arg0.getMessage() != null) {
                            if (arg0.getMessage().contains(
                                    "HttpHostConnectException")) {
                                MyToast.showLong(mContext, "网络已断开");
                            }
                        } else {
                            MyToast.showLong(mContext, "上传图片失败");
                        }
                        LoadDialog.dismiss(mLoadDialog);
                        if (file.exists()) {
                            file.delete();
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<Object> response) {
                        String result = (String) response.result;
                        String resultCode = "";
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            resultCode = jsonObject
                                    .getString(Constant.RESULT_CODE);
                            if (resultCode
                                    .equals(ResultCode.result_ok.resultCode)) {
                                String orinImageUrl = jsonObject
                                        .getString("imageUrl");
                                if (StringUtil.stringIsNull(orinImageUrl)) {
                                    MyToast.showShort(mContext, "上传图片失败");
                                    return;
                                }
                                QuestionUploadImage questionUploadImagePara = setUploadImagePara(bitmap, orinImageUrl);
                                questionAddImageRequest(questionUploadImagePara);
                            } else if (resultCode
                                    .equals(ResultCode.result_000001E.resultCode)) {
                                MyToast.showShort(mContext, R.string.questionlib_09131_000001E);
                            } else if (resultCode
                                    .equals(ResultCode.result_300001E.resultCode)) {
                                MyToast.showShort(mContext, R.string.questionlib_09132_300001E);
                            } else if (resultCode
                                    .equals(ResultCode.result_system_exception_999999E.resultCode)) {
                                MyToast.showShort(mContext, R.string.questionlib_091399_999999E);
                            } else {
                                MyToast.showShort(mContext, "上传图片失败");
                            }
                        } catch (JSONException e) {
                            LogUtil.e("JSON异常", e);
                            MyToast.showShort(mContext, "上传图片失败");
                        } finally {
                            if (file.exists()) {
                                file.delete();
                            }
                            if (!resultCode.equals(ResultCode.result_ok.resultCode)) {
                                LoadDialog.dismiss(mLoadDialog);
                            }
                        }
                    }
                });
    }

    /**
     * 设置图片增加参数
     *
     * @param bitmap
     * @param orinImageUrl
     * @return
     */
    private QuestionUploadImage setUploadImagePara(Bitmap bitmap, String orinImageUrl) {
        QuestionUploadImage questionUploadImage = new QuestionUploadImage();
        questionUploadImage.setExaminationId(mExaminationId);
        questionUploadImage.setQuestionId(mList.get(mPosition).getQuestionId());
        questionUploadImage.setCompressWidth(bitmap.getWidth());
        questionUploadImage.setWidth(bitmap.getWidth());
        questionUploadImage.setHeight(bitmap.getHeight());
        questionUploadImage.setLeftMargin(0);
        questionUploadImage.setTopMargin(0);
        questionUploadImage.setImageUrl(orinImageUrl);
        return questionUploadImage;
    }

    /**
     * 题目增加图片请求
     *
     * @param questionUploadImage
     */
    private void questionAddImageRequest(QuestionUploadImage questionUploadImage) {
        JsonObjectRequest request = mActivity.mRequest.questionAddImageRequest(questionUploadImage,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        getQuestionAddImageListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mActivity.mRequest.disposeError(mContext, mLoadDialog, error, "上传图片失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 题目增加图片监听
     *
     * @param response
     */
    private void getQuestionAddImageListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                String cropImageUrl = response.getString("imageUrl");
                if (StringUtil.stringIsNull(cropImageUrl)) {
                    MyToast.showLong(mContext, "上传图片失败");
                    return;
                }
                mList.get(mPosition).getImageUrls().add(cropImageUrl);
                mQuestionImageAdapter.notifyDataSetChanged();
//                notifyDataSetChanged();
                MyToast.showShort(mContext, "上传成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09111_000001E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09112_300001E);
            } else if (resultCode.equals(ResultCode.result_300024E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09113_300024E);
            } else if (resultCode.equals(ResultCode.result_300027E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09114_300027E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091199_999999E);
            } else {
                MyToast.showShort(mContext, "上传图片失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "上传图片失败");
        } finally {
            LoadDialog.dismiss(mLoadDialog);
        }
    }

    /**
     * 删除题目请求
     *
     * @param question
     */
    private void deleteQuestionRequest(Question question) {
        mLoadDialog = LoadDialog.show(mContext, null, "删除中...", false);
        mBakupList = mList;
        mList.remove(question);
        List<String> questionIds = new ArrayList<>();
        questionIds.add(question.getQuestionId());
        JsonObjectRequest request = mActivity.mRequest.deleteQuestionRequest(mExaminationId, questionIds,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        deleteQuestionListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mList = mBakupList;
                        notifyDataSetChanged();
                        mActivity.mRequest.disposeError(mContext, mLoadDialog, error, "删除失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 删除题目监听
     *
     * @param response
     */
    private void deleteQuestionListener(JSONObject response) {
        String resultCode = "";
        try {
            resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                notifyDataSetChanged();
                MyToast.showShort(mContext, "删除成功");
            } else if (resultCode.equals(ResultCode.result_000001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09151_000001E);
            } else if (resultCode.equals(ResultCode.result_100012E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09152_100012E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.questionlib_09153_300001E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.questionlib_091599_999999E);
            } else {
                MyToast.showShort(mContext, "删除失败");
            }
        } catch (JSONException e) {
            LogUtil.e("JSON异常", e);
            MyToast.showShort(mContext, "删除失败");
        } finally {
            if (!resultCode.equals(ResultCode.result_ok.resultCode) && mBakupList != null) {
                mList = mBakupList;
                notifyDataSetChanged();
            }
            LoadDialog.dismiss(mLoadDialog);
        }
    }

}